package com.example.mvpframe.mvplibrary.rx

import android.app.Activity
import com.example.mvpframe.BuildConfig
import com.example.mvpframe.toast.ToastUtils
import com.google.gson.Gson
import com.tchhy.mvplibrary.presenter.view.BaseView
import com.tchhy.mvplibrary.rx.ServiceCodeEnum
import com.tchhy.provider.data.common.EmptyResp
import com.tchhy.provider.event.UpdataIdEvent
import com.tchhy.provider.rx.RxErrorHandle
import com.trello.rxlifecycle2.LifecycleProvider
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException

/**
 * Describe: RxJava线程戏相关
 *
 */
open class DefaultEmptyObserver(
    var context: Activity,
    val lifecycleProvider: LifecycleProvider<*>,
    val view: BaseView?,
    private val onSuccess: () -> Unit
) : Observer<EmptyResp> {

    open fun onErrorMessage(errorMessage: String) {
        if(!errorMessage.isNullOrEmpty()){
            ToastUtils.show(errorMessage)
        }
        view?.dismissLoading()
    }

    override fun onNext(t: EmptyResp) {
        if (t.status == 0) {
            onSuccess.invoke()
        } else {
            onOtherCode(t.status)
            onErrorMessage(t.message)
        }
    }
    open fun onOtherCode(code: Int) {

    }
    override fun onComplete() {
        view?.dismissLoading()
    }

    override fun onSubscribe(d: Disposable) {
        view?.showLoading()
    }

    override fun onError(e: Throwable) {
        view?.dismissLoading()


        if (e is HttpException) {
            val errorBody = e.response()?.errorBody()!!.string()
            if(e.response()?.code() == 502){
                ToastUtils.show("时间出现异常")
                view?.onError(errorBody)
            }else{
                try {
                    val emptyResponse = Gson().fromJson(errorBody, EmptyResp::class.java)
                    when (emptyResponse.status) {
                        ServiceCodeEnum.CODE_ACCESS_TOKEN_EXPIRED,
                        ServiceCodeEnum.CODE_ACCESS_TOKEN_VALIDATE_ERROR,
                        ServiceCodeEnum.CODE_ACCESS_REFRESH_TOKEN_VALIDATE_ERROR -> {
//                            jumpToLoginActivity()
                        }
                    }
                    if (emptyResponse.status == ServiceCodeEnum.CODE_REMOVED_FAMILY) {
                        if (!emptyResponse.message.isNullOrEmpty()) {
                            val msgs = emptyResponse.message.split("&")
                            if (msgs.size == 2) {
                                ToastUtils.show(msgs[0])
                                EventBus.getDefault().post(UpdataIdEvent(msgs[1]))
                            } else {
                                ToastUtils.show(emptyResponse.message + "")
                            }
                        }
                    } else {
                        if (BuildConfig.DEBUG) {//是否是正式服务器
                            ToastUtils.show("接口异常：响应码：" + e.code() + "\n原因：" + emptyResponse.message)
                        } else {
                            ToastUtils.show(emptyResponse.message + "")
                        }
                    }
                    view?.onError(emptyResponse.message)
                } catch (e: Exception) {
                    if (BuildConfig.DEBUG) {//是否是正式服务器
                        ToastUtils.show("网络连接不稳定，请稍后再试\n" + e.message.toString())
                    } else {
                        ToastUtils.show("网络连接不稳定，请稍后再试" )
                    }

                    view?.onError(errorBody)
                }
            }


        } else {
            ToastUtils.show("网络连接不稳定，请稍后再试")
            view?.onError(RxErrorHandle(e).error())
        }

    }

    /*private fun jumpToLoginActivity() {
        val clz = Class.forName("com.tchhy.tcjk.ui.login.activity.LoginNewActivity");
        val intent = Intent(context, clz)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        UserInfoHelper.clearAccountInfo(context)
        TokenHelper.clearAuthorization(context)
        MedicineUsageNoticeClearUtil.cancelAllTask()
        context.startActivity(intent)
    }*/
}